<script setup>
import { ref, onMounted } from 'vue'
import { encodeText, assembleWsAuthUrl } from './util'


const tte = ref(false)
let audioPlayer = null
let ttsWS = null

onMounted(() => {
  // 初始化音频播放器
  audioPlayer = new window.AudioPlayer('/tts')
  
  // 监听播放结束事件
  audioPlayer.onended = () => {
  }
  
  // 监听错误事件
  audioPlayer.onerror = (error) => {
    console.error('音频播放错误:', error)
  }
})

// 开始播放
const startTTS = async (inputText) => {
  const url = assembleWsAuthUrl();
  ttsWS = new WebSocket(url);
  
  ttsWS.onopen = (e) => {
    audioPlayer.start({
      autoPlay: true,
    });
    var textInfo = inputText || "请输入您要合成的文本";
    
    const data = {
      header: {
        app_id: 'f31bcad0',
        status: 2
      },
      parameter: {
        tts: {
          vcn: "x4_lingxiaoxuan_oral",
          volume: 50,
          rhy: 0,
          speed: 50,
          pitch: 50,
          bgs: 0,
          reg: 0,
          rdn: 0,
          audio: {
            encoding: "raw",
            sample_rate: 16000,
            channels: 1,
            bit_depth: 16,
            frame_size: 0
          }
        }
      },
      payload: {
        text: {
          encoding: "utf8",
          compress: "raw",
          format: "plain",
          status: 2,
          seq: 0,
          text: encodeText(textInfo, 'UTF8')
        }
      }
    };
    ttsWS.send(JSON.stringify(data));
  };
  ttsWS.onmessage = (e) => {
    try {
      const response = JSON.parse(e.data);
      const code = response.header.code;

      if (response.payload) {
        const audio = response.payload.audio.audio;
        const status = response.payload.audio.status;

        if (status === 2) {
          ttsWS.close();
        }
        if (code !== 0) {
          console.log(`call error:${response.message} code is:${code}`);
        } else {
          audioPlayer.postMessage({
            type: "base64",
            data: audio,
            isLastData: status === 2,
          });
        }
      }
    } catch (e) {
      console.error("接收消息解析异常:", e);
    }
  };
  ttsWS.onerror = (e) => {
    console.error(e);
  };
  ttsWS.onclose = (e) => {
    // console.log(e);
  };
}

defineExpose({
  startTTS
})

</script>

<template>
  <div class="tts-container">
  </div>
</template>

<style scoped>
</style>
